#include <winsock2.h>
#include <windows.h>
#include <fcntl.h>
#include <string.h>
#include <stdlib.h>
#include <errno.h>
#include <stdio.h>
#include <conio.h>
#include <iostream>
#include <fstream>
#include <string.h>
#include <stdlib.h>
#include <time.h>




using namespace std;
int connectClient();
int write(char* port, char* inaddress, char* mode, char* data);
int initPort(char* port, char* params);

int readSerialfromFile();
char * sendReceiveData( char *data);
void closeConnection();
char * justReceiveData( char *data);
int writeToFile(char* port, char* inaddress, char* mode, char* data);

int hsock =0;




// The demo is set to read an eps file dump through the serial port
// run this file and hit the print button on the oscilloscope
// remember to set the print options on the oscilloscope to use the RS232 port to print
// set the baud rate to 9600 Hz on the oscilloscope or change this baud rate value 
// in the ethernet_lwip project's main file

int main(int argv, char** argc){


	connectClient();
	

int ret;

// initialize the serial port
ret = initPort("SERL", "");
if (ret !=0)
{
printf("\nerror initalizing the serial\n");
}
else if (ret == 0)
{
printf("\ninitalized serial successfully\n");
}


printf("reading\n");

ret = writeToFile("SERL","","R" ,"");

if (ret !=0)
{
printf("error connecting to client\n");
}
else if (ret == 0)
{
printf("\nno error connecting to client\n");
}



// use this function to send the file C:\\Program Files\\Microsoft Visual Studio 9.0\\VC\\C_API_FILE.EPS
// to the serial port

//readSerialfromFile();




//Use this section of the code to read a waveform dump over the GPIB port from
//the oscilloscope. The printer options on the oscilloscope is set to use the GPIB port to print

/*

ret = initPort("GPIB", "");
if (ret !=0)
{
printf("\nerror initalizing the serial\n");
}
else if (ret == 0)
{
printf("\ninitalized serial successfully\n");
}

ret = write("GPIB","01","R" ,"");

if (ret !=0)
{
printf("error GPIB read\n");
}
else if (ret == 0)
{
printf("\nno error GPIB read\n");
}*/
return 0;
}


int readSerialfromFile()
{
	 ifstream in("C:\\Program Files\\Microsoft Visual Studio 9.0\\VC\\C_API_FILE.EPS", ios::in | ios::binary);

	if(!in) {
	 printf("not able to open the file");
	 return (-1);
	}

	char temp [1001] = "\0";
	
	while(!in.eof())
	{
		char temp [1001] = "\0";
		in.read(temp,1000);
		//printf ("%s",temp);
		
            int ret;
            ret = write("SERL","","W" ,temp);
        if (ret !=0)
         {
          printf("error connecting to client");
         }
         else if (ret == 0)
       {
         printf("no error connecting to client");
          }

	}  
	in.close();
	return 0;
}

int readParallelfromFile()
{
	 ifstream in("test.txt", ios::in | ios::binary);

	if(!in) {
	 printf("not able to open the file");
	 return (-1);
	}
	int start =1;

	char temp [101] = "\0";
	
	while(!in.eof())
	{
		in.read(temp,100);
            int ret;
            if (start == 1)
            {
            ret = write("PARL","","W" ,temp);
            start =0;
            }
            else
            {
            ret = write("PARL","","F" ,temp);
            }
        if (ret !=0)
         {
          printf("error connecting to client");
         }
         else if (ret == 0)
       {
         printf("no error connecting to client");
          }

	}  
	in.close();
	return 0;
}

int connectClient()
{


	//The port and address you want to connect to
	int host_port= 5436;
	char* host_name="192.168.0.2";

	//Initialize socket support WINDOWS ONLY!
	unsigned short wVersionRequested;
	WSADATA wsaData;
	int err;
	wVersionRequested = MAKEWORD( 2, 2 );
 	err = WSAStartup( wVersionRequested, &wsaData );
	if ( err != 0 || ( LOBYTE( wsaData.wVersion ) != 2 ||
		    HIBYTE( wsaData.wVersion ) != 2 )) {
	    fprintf(stderr, "Could not find useable sock dll %d\n",WSAGetLastError());
		return -1;
	}

	//Initialize sockets and set any options
	
	int * p_int ;
	hsock = socket(AF_INET, SOCK_STREAM, 0);
	if(hsock == -1){
		printf("Error initializing socket %d\n",WSAGetLastError());
		return -1;
	}
	
	p_int = (int*)malloc(sizeof(int));
	*p_int = 1;
	if( (setsockopt(hsock, SOL_SOCKET, SO_REUSEADDR, (char*)p_int, sizeof(int)) == -1 )||
		(setsockopt(hsock, SOL_SOCKET, SO_KEEPALIVE, (char*)p_int, sizeof(int)) == -1 ) ){
		printf("Error setting options %d\n", WSAGetLastError());
		free(p_int);
		return -1;
	}
	free(p_int);

	//Connect to the server
	struct sockaddr_in my_addr;

	my_addr.sin_family = AF_INET ;
	my_addr.sin_port = htons(host_port);
	
	memset(&(my_addr.sin_zero), 0, 8);
	my_addr.sin_addr.s_addr = inet_addr(host_name);


	if( connect( hsock, (struct sockaddr*)&my_addr, sizeof(my_addr)) == SOCKET_ERROR ){
		fprintf(stderr, "Error connecting socket %d\n", WSAGetLastError());
		return -1;
	}

	//Now lets do the client related stuff
 
	
	return 0;


}


char * sendReceiveData( char *data)
{
char *buffer;
buffer = (char*) malloc (1025);

int buffer_len  = 1024;
	int bytecount;
	
	int c;
	memset(buffer, '\0', buffer_len);

	//for(char* p=buffer ; (c=getch())!=13 ; p++){
		//printf("%c", c);
		//*p = c;
	//}
	strcpy(buffer,data);
	//printf ("In the send receive: %s",buffer);
	
	if( (bytecount=send(hsock, buffer, buffer_len,0))==SOCKET_ERROR){
		fprintf(stderr, "Error sending data %d\n", WSAGetLastError());
		return buffer;
	}
	printf("Sent bytes %d\n", bytecount);

memset(buffer, '\0', buffer_len);

	if((bytecount = recv(hsock, buffer, buffer_len, 0))==SOCKET_ERROR){
		fprintf(stderr, "Error receiving data %d\n", WSAGetLastError());
		return buffer;
	}


	printf("Received string: %s\n",buffer);

	return buffer;	
}

char * justReceiveData( char *data)
{

	char *buffer;
buffer = (char*) malloc (1025);
int buffer_len  = 1024;
	int bytecount;
memset(buffer, '\0', buffer_len);

if((bytecount = recv(hsock, buffer, buffer_len, 0))==SOCKET_ERROR){
		fprintf(stderr, "Error receiving data %d\n", WSAGetLastError());
		return buffer;
	}


	printf("Received string: %s\n",buffer);

	return buffer;	


}
void closeConnection()
{

closesocket(hsock);
}


/*

int writeToFile(char* port, char* inaddress, char* mode, char* data)
{
	
char buffer[1024];
	//char data_ret[1024];
char *data_ret;
data_ret = (char*) malloc (1024);

int ret;
if(strcmp(port,"GPIB") == 0)
	{
		strcpy(buffer,"GPIB");
		strcat(buffer,inaddress);
		strcat(buffer,mode);
		strcat(buffer,data);
	}
else if(strcmp(port,"PARL") == 0)
	{
	strcpy(buffer,"PARL");
		strcat(buffer,mode);
		strcat(buffer,data);
	}

else if(strcmp(port,"SERL") == 0)
	{
		strcpy(buffer,"SERL");
		strcat(buffer,mode);
		strcat(buffer,data);
	}
	
ofstream out("C_API_FILE.TXT", ios::out | ios::binary);
	if(!out) 
	{
		printf("cannot open the file");
		return -1;
	}


char start[1200];
	strcpy(start, "this is the start message\n");
	out.write(start,strlen(start));

data_ret = sendReceiveData(buffer);
int length = strlen(data_ret);

strcpy(start,data_ret);
//strncpy(start,data_ret,length-1);
start[length-1]='\0';
out.write(start,strlen(start));

// WRITE TO A FILE 

while (data_ret[length-1] == '@')
{
 data_ret =justReceiveData(buffer);
length = strlen(data_ret);
strcpy(start,data_ret);
//strncpy(start,data_ret,length-1);
start[length-1]='\0';

out.write(start,strlen(start));
}

strcpy(start, "\nthis is the end message");
out.write(start,strlen(start));
printf("Done reading..............");
	out.close();

return 0;
}

*/

int write(char* port, char* inaddress, char* mode, char* data)
{
	
char buffer[1024];
	//char data_ret[1024];
char *data_ret;
data_ret = (char*) malloc (1024);

int ret;
if(strcmp(port,"GPIB") == 0)
	{
		strcpy(buffer,"GPIB");
		strcat(buffer,inaddress);
		strcat(buffer,mode);
		strcat(buffer,data);
	}
else if(strcmp(port,"PARL") == 0)
	{
	strcpy(buffer,"PARL");
		strcat(buffer,mode);
		strcat(buffer,data);
	}

else if(strcmp(port,"SERL") == 0)
	{
		strcpy(buffer,"SERL");
		strcat(buffer,mode);
		strcat(buffer,data);
	}
	
ofstream out("C_API_FILE.TXT", ios::out | ios::binary);
	if(!out) 
	{
		printf("cannot open the file");
		return -1;
	}


char start[1200];
	strcpy(start, "this is the start message\n");
	printf("%s",start);

data_ret = sendReceiveData(buffer);
int length = strlen(data_ret);

strcpy(start,data_ret);
//strncpy(start,data_ret,length-1);
start[length-1]='\0';
	printf("%s",start);


// WRITE TO A FILE 


while (data_ret[length-1] == '@')
{
 data_ret =justReceiveData(buffer);
length = strlen(data_ret);
strcpy(start,data_ret);
//strncpy(start,data_ret,length-1);
start[length-1]='\0';

	printf("%s",start);
}

strcpy(start, "\nthis is the end message");
	printf("%s",start);
printf("Done reading..............");
	

return 0;
}

int writeToFile(char* port, char* inaddress, char* mode, char* data)
{
	
char buffer[1024];
	//char data_ret[1024];
char *data_ret;
data_ret = (char*) malloc (1024);

int ret;
if(strcmp(port,"GPIB") == 0)
	{
		strcpy(buffer,"GPIB");
		strcat(buffer,inaddress);
		strcat(buffer,mode);
		strcat(buffer,data);
	}
else if(strcmp(port,"PARL") == 0)
	{
	strcpy(buffer,"PARL");
		strcat(buffer,mode);
		strcat(buffer,data);
	}

else if(strcmp(port,"SERL") == 0)
	{
		strcpy(buffer,"SERL");
		strcat(buffer,mode);
		strcat(buffer,data);
	}
	
ofstream out("C_API_FILE.EPS", ios::out | ios::binary);
	if(!out) 
	{
		printf("cannot open the file");
		return -1;
	}


char start[1200];
	strcpy(start, "this is the start message\n");
	printf("%s",start);

data_ret = sendReceiveData(buffer);
int length = strlen(data_ret);

strcpy(start,data_ret);
//strncpy(start,data_ret,length-1);
start[length-1]='\0';
	printf("%s",start);
out.write(start,strlen(start));

// WRITE TO A FILE 


while (data_ret[length-1] == '@')
{
 data_ret =justReceiveData(buffer);
length = strlen(data_ret);
strcpy(start,data_ret);
//strncpy(start,data_ret,length-1);
start[length-1]='\0';
out.write(start,strlen(start));
	printf("%s",start);
}

strcpy(start, "\nthis is the end message");
	printf("%s",start);
	//out.write(start,strlen(start));
	out.close();
printf("Done reading..............");
	

return 0;
}
// the first characters will be INIT
int initPort(char* port, char* params)
{
//check sizes of incoming strings for validity
//Check if port exists from previous init
	int writeLength;
	char* toWrite;

	if(strcmp(port,"GPIB") == 0)
	{
		writeLength = 4;
		toWrite = (char*) malloc (writeLength);
		strcpy(toWrite, "INTG");
	}
	else if(strcmp(port,"PARL") == 0)
	{
		writeLength = 4 + strlen(params);
		toWrite = (char*) malloc (writeLength);
		strcpy(toWrite, "INTP");
		strcat(toWrite, params);
	}

	else if(strcmp(port,"SERL") == 0)
	{
		writeLength = 4 + strlen(params);
		toWrite = (char*) malloc (writeLength);
		strcpy(toWrite, "INTS");
		strcat(toWrite, params);
	}
toWrite[writeLength+1] = '\0';
// WRITE TO THE CLIENT
	toWrite = sendReceiveData(toWrite);
	return 0;
}